package org.wyz;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.wyz.mapreduce.pagerank.PageRankMapper;
import org.wyz.mapreduce.pagerank.PageRankReducer;
import org.wyz.mapreduce.pagerank.PageWritable;


public class PageRank {
    private static final String[] ARGS = {"data/input/pagerank", "data/output/pagerank"};

    private static final int MAX_EPOCH = 5;
    private static int EPOCH = 0;

    public int run(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "pagerank");
        job.setJarByClass(this.getClass());

        job.setMapperClass(PageRankMapper.class);
        job.setReducerClass(PageRankReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(PageWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        if (EPOCH == 0) {
            FileInputFormat.addInputPath(job, new Path(args[0]));
        } else {
            FileInputFormat.addInputPath(job, new Path(args[1] + (EPOCH - 1)));
        }
        FileOutputFormat.setOutputPath(job, new Path(args[1] + EPOCH));

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        PageRank pr = new PageRank();
        for (EPOCH = 0; EPOCH < MAX_EPOCH; EPOCH++) {
            int res = pr.run(ARGS);
            if (res != 0) {
                System.exit(res);
            }
        }
    }

}
